#include "SocketStream.h"

namespace sylar
{
	sylar::SocketStream::SocketStream(Socket::ptr sock, bool owner):m_sock(sock),m_owner(owner)
	{
		
	}

	SocketStream::~SocketStream()
	{
		if (m_owner && m_sock)
		{
			m_sock->close();
		}
	}

	int SocketStream::read(void* buffer, size_t length)
	{
		if (!isConnect())
		{
			return -1;
		}
		return m_sock->recv(buffer,length);
	}

	int SocketStream::read(ByteArray::ptr buffer, size_t length)
	{
		if (!isConnect())
		{
			return -1;
		}
		std::vector<iovec> iovecs;
		buffer->getWriteBuffers(iovecs,length);
		int rt= m_sock->recv(&iovecs[0],iovecs.size());
		if (rt>0)
		{
			buffer->setPosition(buffer->getPosition() + rt);
		}
		return rt;

	}

	int SocketStream::write(const void* buffer, size_t length)
	{
		if (!isConnect())
		{
			return -1;
		}
		return m_sock->send(buffer, length);
	}

	int SocketStream::write(ByteArray::ptr buffer, size_t length)
	{
		if (!isConnect())
		{
			return -1;
		}
		std::vector<iovec> iovecs;
		buffer->getReadBuffers(iovecs, length);
		int rt = m_sock->send(&iovecs[0], iovecs.size());
		if (rt > 0)
		{
			buffer->setPosition(buffer->getPosition() + rt);
		}
		return rt;
	}

	void SocketStream::close()
	{
		if (m_sock)
		{
			m_sock->close();
		}
	}

}

